// dh-recycle-cleaner 云对象
// 回收站定时清理器

const db = uniCloud.database()
const dbCmd = db.command
const { batchCleanupRecordFiles, getTableFileFields } = require('dh-common')

module.exports = {
	/**
	 * 自动清理过期的软删除记录
	 * @param {number} daysAgo - 清理多少天前的记录，默认30天
	 */
	async autoCleanup(daysAgo = 30) {
		try {
			const threshold = Date.now() - daysAgo * 24 * 60 * 60 * 1000
			
			const tables = [
				'dh-hospitals', 'dh-doctors', 'dh-nurses', 'dh-staff_users',
				'dh-patients', 'dh-services', 'dh-products', 'dh-doctor_schedules',
				'dh-appointments', 'dh-medical_records', 'dh-reviews', 
				'dh-consultations', 'dh-income_records', 'dh-leave_requests',
				'dh-purchase_requests', 'dh-inventory', 'dh-inventory_logs',
				'dh-hospital_promotions', 'dh-hospital_banners', 
				'dh-promotion_rules', 'dh-medical_authorizations'
			]
			
			const summary = {
				totalRecords: 0,
				totalFiles: 0,
				details: []
			}
			
			for (const tableName of tables) {
				try {
					const result = await this._cleanupTable(tableName, threshold)
					summary.totalRecords += result.recordsDeleted
					summary.totalFiles += result.filesDeleted
					summary.details.push(result)
				} catch (err) {
					console.error(`清理表${tableName}失败:`, err)
					summary.details.push({
						tableName,
						error: err.message,
						recordsDeleted: 0,
						filesDeleted: 0
					})
				}
			}
			
			return {
				code: 200,
				message: `清理完成：删除${summary.totalRecords}条记录，${summary.totalFiles}个文件`,
				data: summary
			}
		} catch (err) {
			console.error('[autoCleanup] 自动清理失败:', err)
			return {
				code: 500,
				message: err.message || '自动清理失败',
				data: null
			}
		}
	},
	
	/**
	 * 清理单个表的过期数据
	 * @param {string} tableName - 表名
	 * @param {number} threshold - 时间阈值（时间戳）
	 * @returns {Object} 清理结果
	 */
	async _cleanupTable(tableName, threshold) {
		try {
			// 1. 查询过期的软删除记录
			const recordsRes = await db.collection(tableName)
				.where({
					is_deleted: true,
					deleted_at: dbCmd.lt(threshold)
				})
				.get()
			
			const records = recordsRes.data || []
			
			if (records.length === 0) {
				return {
					tableName,
					recordsDeleted: 0,
					filesDeleted: 0
				}
			}
			
			// 2. 提取所有文件
			const fileFields = getTableFileFields(tableName)
			const allFiles = []
			
			records.forEach(record => {
				fileFields.forEach(field => {
					const value = record[field]
					
					if (!value) return
					
					// 处理file对象
					if (typeof value === 'object' && value.url) {
						allFiles.push(value.url)
					}
					// 处理字符串
					else if (typeof value === 'string' && value.startsWith('cloud://')) {
						allFiles.push(value)
					}
					// 处理数组
					else if (Array.isArray(value)) {
						value.forEach(item => {
							if (typeof item === 'object' && item.url) {
								allFiles.push(item.url)
							} else if (typeof item === 'string' && item.startsWith('cloud://')) {
								allFiles.push(item)
							}
						})
					}
				})
			})
			
			// 3. 永久删除数据库记录
			for (const record of records) {
				await db.collection(tableName).doc(record._id).remove()
			}
			
			// 4. 删除云存储文件
			let filesDeleted = 0
			if (allFiles.length > 0) {
				try {
					const deleteResult = await uniCloud.deleteFile({
						fileList: allFiles
					})
					
					if (deleteResult.fileList && Array.isArray(deleteResult.fileList)) {
						filesDeleted = deleteResult.fileList.filter(f => f.code === 0).length
					}
				} catch (fileErr) {
					console.error(`删除文件失败 - ${tableName}:`, fileErr)
				}
			}
			
			console.log(`[_cleanupTable] ${tableName}: 删除${records.length}条记录，${filesDeleted}个文件`)
			
			return {
				tableName,
				recordsDeleted: records.length,
				filesDeleted
			}
		} catch (err) {
			console.error(`[_cleanupTable] 清理表${tableName}失败:`, err)
			throw err
		}
	},
	
	/**
	 * 手动触发清理（测试用）
	 */
	async triggerManualCleanup(daysAgo = 30) {
		return await this.autoCleanup(daysAgo)
	},
	
	/**
	 * 获取待清理的数据统计
	 * @param {number} daysAgo - 天数
	 * @returns {Object} 统计信息
	 */
	async getCleanupPreview(daysAgo = 30) {
		try {
			const threshold = Date.now() - daysAgo * 24 * 60 * 60 * 1000
			
			const tables = [
				'dh-hospitals', 'dh-doctors', 'dh-nurses', 'dh-staff_users',
				'dh-patients', 'dh-services', 'dh-products', 'dh-doctor_schedules',
				'dh-appointments', 'dh-medical_records', 'dh-reviews', 
				'dh-consultations', 'dh-income_records', 'dh-leave_requests',
				'dh-purchase_requests', 'dh-inventory', 'dh-inventory_logs',
				'dh-hospital_promotions', 'dh-hospital_banners', 
				'dh-promotion_rules', 'dh-medical_authorizations'
			]
			
			const stats = {}
			let total = 0
			
			// 并行查询
			const results = await Promise.all(
				tables.map(tableName =>
					db.collection(tableName)
						.where({
							is_deleted: true,
							deleted_at: dbCmd.lt(threshold)
						})
						.count()
				)
			)
			
			tables.forEach((tableName, index) => {
				const count = results[index].total || 0
				stats[tableName] = count
				total += count
			})
			
			return {
				code: 200,
				message: '预览成功',
				data: {
					daysAgo,
					threshold,
					total,
					stats
				}
			}
		} catch (err) {
			console.error('[getCleanupPreview] 获取清理预览失败:', err)
			return {
				code: 500,
				message: err.message || '获取预览失败',
				data: null
			}
		}
	}
}

